#include "errordialogmanager.h"
#include "networkworker.h"
#include "source/logger.h"
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>
#include <QHttpMultiPart>
#include <QTimer>
#include <QTimeZone>
#include <QStandardPaths>
#include <QProcess>

NetworkWorker::NetworkWorker(QObject *parent)
    : QThread(parent), m_serverConnected(false),
    m_latestVersion("还未查询到信息"),
    m_updateContent("还未查询到信息"),
    m_deviceName("还未查询到信息"),
    m_owner("还未查询到信息"),
    m_endUser("还未查询到信息"),
    m_releasedBy("还未查询到信息"),
    m_networkManager(new QNetworkAccessManager(this))
{
    m_currentVersion = "1.0.0"; // Initialize current version

}

void NetworkWorker::run()
{
    exec();
}

void NetworkWorker::setencryptSequence(QByteArray encryptSequence)
{
    encryptSequence_ = encryptSequence;
}

void NetworkWorker::connectToServer()
{
    QUrl url(urlPath+"check_connect/");
    QNetworkRequest request(url);
    request.setRawHeader("X-Encrypted-Sequence", encryptSequence_);
    QNetworkReply *reply = m_networkManager->get(request);
    connect(reply, &QNetworkReply::finished, this, [this]() {
        QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
        if (reply->error() == QNetworkReply::NoError) {
            // 读取服务器返回的数据
            QByteArray responseData = reply->readAll();
            QString responseString(responseData);

            m_serverConnected = true;
            //LogDebug << "Connected to server. Response:" << responseString;
        } else {
            m_serverConnected = false;
            LogDebug << "ERROR" ;
            handleNetworkError(reply);
        }
        reply->deleteLater();
    });
}

void NetworkWorker::sendRunningStatus()
{
    QUrl url(urlPath+"status/");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject json;
    json["status"] = "running";

    QNetworkReply *reply = m_networkManager->post(request, QJsonDocument(json).toJson());
    connect(reply, &QNetworkReply::finished, this, [this]() {
        QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
        if (reply->error() == QNetworkReply::NoError) {
            m_serverConnected = true;
            emit serverConnectedChanged(true);
            log("Connected to server.");
        } else {
            m_serverConnected = false;
            emit serverConnectedChanged(false);
            log("Failed to connect to server.");
        }
        reply->deleteLater();
    });
}

void NetworkWorker::sendCompressedImage(const QString &imagePath)
{
    QFile file(imagePath);
    if (!file.open(QIODevice::ReadOnly)) {
        log("Failed to open image file.");
        return;
    }

    QByteArray imageData = file.readAll();
    file.close();

    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"; filename=\"image.jpg\""));
    imagePart.setBody(imageData);

    multiPart->append(imagePart);

    QNetworkRequest request(QUrl("http://yourserver.com/upload"));
    QNetworkReply *reply = m_networkManager->post(request, multiPart);
    multiPart->setParent(reply);

    // connect(reply, &QNetworkReply::finished, this, [this]() {
    //     QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    //     handleServerResponse(reply);
    // });
}

void NetworkWorker::checkForUpdates()
{
    QUrl url(urlPath+"check-updates/");
    QNetworkRequest request(url);
    request.setRawHeader("X-Encrypted-Sequence", encryptSequence_);
    QNetworkReply *reply = m_networkManager->get(request);

    connect(reply, &QNetworkReply::finished, [this, reply]() {
        if (reply->error() == QNetworkReply::NoError) {
            QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll());
            QJsonObject jsonObject = jsonResponse.object();
            m_latestVersion = QString::fromUtf8(jsonObject.value("version").toString().toUtf8());
            LogDebug<< "m_latestVersion" <<m_latestVersion;
            m_updateContent = jsonObject["content"].toString();
            m_updateTime = QDateTime::fromString(jsonObject["time"].toString(), Qt::ISODate);
            m_releasedBy = jsonObject["released_by"].toString();
            emit updateContentChanged();
            emit updateTimeChanged();
            emit latestVersionChanged();

           LogDebug << "Update information received.";
        } else {
           handleNetworkError(reply);
        }
        reply->deleteLater();
    });
}

void NetworkWorker::getDeviceInfo()
{
    QUrl url(urlPath + "get_device_info/");
    QNetworkRequest request(url);
    request.setRawHeader("X-Encrypted-Sequence", encryptSequence_);
    QNetworkReply *reply = m_networkManager->get(request);

    // 连接信号槽
    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();

            // Ensure response data is valid UTF-8
            QString responseString = QString::fromUtf8(responseData);

            QJsonParseError parseError;
            QJsonDocument jsonResponse = QJsonDocument::fromJson(responseString.toUtf8(), &parseError);

            if (jsonResponse.isNull()) {
                log("Failed to parse JSON response.");
                qDebug() << "JSON parse error:" << parseError.errorString();
                return;
            }
            QJsonObject jsonObject = jsonResponse.object();
            // 直接从 QJsonValue 中读取字符串，并确保转换为 UTF-8
            m_deviceName = QString::fromUtf8(jsonObject.value("device_name").toString().toUtf8());
            m_registrationDate = QDateTime::fromString(jsonObject.value("registration_date").toString(), Qt::ISODate);
            m_owner = QString::fromUtf8(jsonObject.value("owner").toString().toUtf8());
            m_expiryDate = QDateTime::fromString(jsonObject.value("expiry_date").toString(), Qt::ISODate);
            m_endUser = QString::fromUtf8(jsonObject.value("end_user").toString().toUtf8());

            m_deviceName = jsonObject["device_name"].toString();
            m_registrationDate = QDateTime::fromString(jsonObject["registration_date"].toString(), Qt::ISODate);
            //获取北京时间对象
            QTimeZone beijingTime("Asia/Shanghai");
            m_registrationDate = m_registrationDate.toTimeZone(beijingTime);
            //设置一个String类型变量
            m_stregistrationDate = m_registrationDate.toString("yyyy-MM-dd dddd");
            m_owner = jsonObject["owner"].toString();
            m_expiryDate = QDateTime::fromString(jsonObject["expiry_date"].toString(), Qt::ISODate);
            m_expiryDate = m_expiryDate.toTimeZone(beijingTime);
            //设置一个String类型变量
            m_stexpiryDate = m_expiryDate.toString("yyyy-MM-dd dddd");

            m_endUser = jsonObject["end_user"].toString();

            emit deviceInfoChanged();
            log("Device information received.");
        } else {
            handleNetworkError(reply);
        }
        reply->deleteLater();
    });
}

void NetworkWorker::downloadUpdate()
{
    LogDebug << "m_latestVersion: " << m_latestVersion;
    if (m_latestVersion.isEmpty()) {
        LogWarning << "NetworkWorker::downloadUpdate Error: Latest version is empty";
        return;
    }

    QUrl url(urlPath + "download_update/" + m_latestVersion + "/");
    QNetworkRequest request(url);
    request.setRawHeader("X-Encrypted-Sequence", encryptSequence_);
    QNetworkReply *reply = m_networkManager->get(request);

    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray data = reply->readAll();
            QFile file(downloadPath);
            if (file.open(QIODevice::WriteOnly)) {
                file.write(data);
                file.close();
                LogDebug << "Update package downloaded and saved to " + downloadPath;
                // Add extraction logic here if needed

                QProcess unzipProcess;
                  unzipProcess.start("unzip", QStringList() << "-o" << downloadPath << "-d" << extractPath);
                unzipProcess.waitForFinished();
                if (unzipProcess.exitStatus() == QProcess::NormalExit && unzipProcess.exitCode() == 0) {
                    LogDebug << "Update package extracted to " + extractPath;
                    // 替换更新内容并重启应用程序
                    //restartApplication();
                }else {
                    LogWarning << "Failed to extract the update package: " << downloadPath << " -d " << extractPath;
                }

            } else {
                LogWarning << "Failed to save the update package" << downloadPath;
            }
        } else {
            handleNetworkError(reply);
        }
        reply->deleteLater();
    });
}

void NetworkWorker::handleNetworkError(QNetworkReply *reply)
{
    QNetworkReply::NetworkError error = reply->error();
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (error == QNetworkReply::HostNotFoundError || error == QNetworkReply::ConnectionRefusedError) {
        LogWarning << "NetworkWorker::downloadUpdate Error: Network not connected";
         ErrorDialogManager::instance().showNonBlockingError("网络连接失败","无法连接到网络");
        // Perform actions for network not connected
    } else {
        QString errorMessage = reply->errorString();
        LogWarning << "Failed to download the update package: " << errorMessage;

        switch (statusCode) {
        case 400:
            LogWarning << "Error: Missing encrypted sequence";
            ErrorDialogManager::instance().showNonBlockingError("系统停机","未添加授权信息");
            // Perform actions for missing encrypted sequence
            break;
        case 403:
            LogWarning << "Error: Invalid sequence";
            ErrorDialogManager::instance().showNonBlockingError("系统停机","授权信息错误无法授权");
            // Perform actions for invalid sequence
            break;
        case 404:
            LogWarning << "Error: Device authorization expired";
            ErrorDialogManager::instance().showNonBlockingError("系统停机","404报错");
            // Perform actions for expired authorization
            break;
        case 405:
            LogWarning << "Error: The authorization time has expired";
            // Perform actions for expired authorization
            ErrorDialogManager::instance().showNonBlockingError("系统暂停","授权信息时间已到");
            break;
        default:
            LogWarning << "HTTP error code: " << statusCode;
            ErrorDialogManager::instance().showNonBlockingError("系统停机","其他报错，授权故障");

            // Perform actions for other HTTP errors
            break;
        }
    }
}

void NetworkWorker::log(const QString &message)
{
    LogDebug << "NetworkWorker" << message;
}

